/**
 * 
 */
package com.juyu.miliao.api.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * @author pengs
 *
 */
public class XmlUtil {
	public static String payInfoToXML(Map<String, String> map) {
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("xml");
		if (map != null) {
			Iterator<String> it = map.keySet().iterator();
			while (it.hasNext()) {
				String key = (String) it.next();
				Element param = root.addElement(key);
				Object obj = map.get(key);
				if (obj != null) {
					if (obj instanceof java.lang.Integer) {
						param.addText(String.valueOf(obj));
					} else {
						param.addText((String) obj);
					}
				}
			}
		}
		return document.asXML();
	}

	public static Map<String, String> parseXml(String xml) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		Document document = DocumentHelper.parseText(xml);
		Element root = document.getRootElement();
		@SuppressWarnings("unchecked")
		List<Element> elementList = root.elements();
		for (Element e : elementList) {
			map.put(e.getName(), e.getText());
		}
		return map;
	}

	public static String returnInfoToXML(Map<String, String> map) {
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("xml");
		if (map != null) {
			Iterator<String> it = map.keySet().iterator();
			while (it.hasNext()) {
				String key = (String) it.next();
				Element param = root.addElement(key);
				String value = map.get(key);
				if (value != null) {
					param.addCDATA(value);
				}
			}
		}
		return document.asXML();
	}
}
